package com.chenyun.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.chenyun.system.model.SysMenu;
import com.chenyun.system.service.ISysMenuService;
import com.chenyun.boot.web.controller.BaseController;
import com.chenyun.common.annotation.Log;
import com.chenyun.common.constants.UserConstants;
import com.chenyun.common.enums.operlog.BusinessTypeEnum;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单信息-admin")
public class SysMenuController extends BaseController<ISysMenuService, SysMenu> {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     * 不是树形 也不分页
     */
    @ApiOperation("获取菜单列表")
    @PostMapping("/list")
    @SaCheckPermission("system:menu:list")
    public AjaxResult list(@RequestBody SysMenu menu) {
        Long userId = Convert.toLong(getUserId());
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.SUCCESS(menus);
    }

    /**
     * 获取菜单列表 树形 ,返回值为List<sysmenu>
     *
     * @param menu
     * @return
     */
    @ApiOperation("获取菜单列表-树形")
    @PostMapping("/listTree")
    @SaCheckPermission("system:menu:listTree")
    public AjaxResult listTree(@RequestBody SysMenu menu) {
        Long userId = Convert.toLong(getUserId());
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        List<SysMenu> menuTrees = menuService.buildMenuTree(menus);
        return AjaxResult.SUCCESS(menuTrees);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperation("根据菜单编号获取详细信息")
    @GetMapping(value = "/{menuId}")
    @SaCheckPermission("system:menu:info")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        return AjaxResult.SUCCESS(menuService.selectMenuById(menuId));
    }


    /**
     * 获取菜单下拉树列表
     */
    @ApiOperation("获取菜单下拉树列表")
    @PostMapping("/treeselect")
    @SaCheckPermission("system:menu:treeselect")
    public AjaxResult treeselect(@RequestBody SysMenu menu) {
        Long userId = Convert.toLong(getUserId());
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.SUCCESS(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @ApiOperation("加载对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    @SaCheckPermission("system:menu:roleMenuTreeselect")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = Convert.toLong(getUserId());
        List<Long> longs = menuService.selectMenuListByRoleId(roleId);
        return AjaxResult.SUCCESS(longs);
    }

    /**
     * 新增菜单
     */
    @ApiOperation("新增菜单")
    @PostMapping()
    @SaCheckPermission("system:menu:add")
    @Log(title = "新增菜单", businessType = BusinessTypeEnum.INSERT, desc = "'新增菜单['+#menu.getMenuName()+']'")
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.FAIL("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.isHttp(menu.getPath())) {
            return AjaxResult.FAIL("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
//        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @ApiOperation("修改菜单")
    @SaCheckPermission("system:menu:edit")
    @PostMapping(value = "edit", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Log(title = "修改菜单", businessType = BusinessTypeEnum.UPDATE, desc = "'修改菜单['+#menu.getMenuName()+']'")
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.FAIL("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.isHttp(menu.getPath())) {
            return AjaxResult.FAIL("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return AjaxResult.FAIL("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
//        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @ApiOperation("删除菜单")
    @PostMapping("del/{menuId}")
    @SaCheckPermission("system:menu:del")
    @Log(title = "删除菜单", businessType = BusinessTypeEnum.DELETE, desc = "'删除菜单['+#menuId+']'")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return AjaxResult.FAIL("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return AjaxResult.FAIL("菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = Convert.toLong(getUserId());
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        //测试
    //    List<SysMenu> collect = menus.stream().filter(p -> p.getMenuId().intValue() == 2210).collect(Collectors.toList());
//     return AjaxResult.SUCCESS(menuService.buildMenus(menus));
//        return AjaxResult.SUCCESS(menuService.buildMenusByMap(collect));
        return AjaxResult.SUCCESS(menuService.buildMenusPureAdmin(menus));
    }



}